package com.gengzp.rpc.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.lang.reflect.Type;

/**
 * @ClassName RpcJsonUtils
 * @Description 远程调用框架封装json转换工具类
 * @Author gengzp
 * @Date 2025/6/1 16:50
 */
public class RpcJsonUtils {

    private final static ObjectMapper objectMapper = initObjectMapper();

    private static ObjectMapper initObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略空对象序列化异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 支持 Java 8 时间 API（LocalDateTime 等）
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    private RpcJsonUtils() {
    }

    /**
     * 转换对象为指定数据类型
     */
    public static Object convertMap2Object(Object obj, Class<?> clazz) {
        return objectMapper.convertValue(obj, clazz);
    }

    /**
     * 将 json 转为对象
     */
    public static <T> T readValue(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON 反序列化失败", e);
        }
    }

    /**
     * 将 json 转为对象
     */
    public static <T> T readValue(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("JSON 反序列化失败", e);
        }
    }

    /**
     * 转换对象为指定类型
     *
     * @param source 对象
     * @param targetType 目标类型
     * @return 目标对象
     * @param <T> 目标对象类型
     */
    public static <T> T convert2Object(Object source, Type targetType) {
        if (source == null) {
            return null;
        }

        try {
            ObjectMapper mapper = new ObjectMapper();

            // 如果是 Map 或 List 等结构，需要先转成 JSON 字符串再处理泛型
            String json = mapper.writeValueAsString(source);

            // 使用 TypeReference 支持泛型
            return mapper.readValue(json, mapper.getTypeFactory().constructType(targetType));
        } catch (Exception e) {
            throw new RuntimeException("转换失败", e);
        }
    }

    /**
     * 将对象转为json
     *
     * @param obj 对象
     * @return json字符串
     */
    public static String writeValueAsString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("JSON 序列化失败", e);
        }
    }

}
